package org.springblade.common.mq;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.PropertyValueConst;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.thierrysquirrel.annotation.*;
import com.google.protobuf.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.rescue.RescueTrappedNoticeDTO;
import org.springblade.modules.admin.entity.RescueNotice;
import org.springblade.modules.admin.entity.RescueNoticeTask;
import org.springblade.modules.admin.entity.RescueNoticeTaskDetail;
import org.springblade.modules.admin.enums.NoticeTaskStatusEnum;
import org.springblade.modules.admin.enums.RescueNoticeConfirmTypeEnum;
import org.springblade.modules.admin.event.RescueTrappedNoticeEvent;
import org.springblade.modules.admin.service.IRescueNoticeService;
import org.springblade.modules.admin.service.IRescueNoticeTaskDetailService;
import org.springblade.modules.admin.service.IRescueNoticeTaskService;
import org.springblade.modules.system.entity.TenantConfig;
import org.springblade.modules.system.service.TenantConfigService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @Author ysq
 * @Date 2025/07/17
 * @Description 救援延迟消息接收
 */
@Component
@Slf4j
@RocketListener(groupID = "GID_RESCUE_DELAY", messageModel = PropertyValueConst.BROADCASTING)
public class RescueDelayReceive {

	@Resource
	private IRescueNoticeTaskService rescueNoticeTaskService;
	@Resource
	private IRescueNoticeTaskDetailService rescueNoticeTaskDetailService;
	@Resource
	private Environment environment;
	@Resource
	private IRescueNoticeService rescueNoticeService;
	@Resource
	private ApplicationEventPublisher applicationEventPublisher;
	@Resource
	private TenantConfigService tenantConfigService;

	@MessageListener(topic = "rescue_delay")
	public void message(String message) throws ServiceException {
		log.info("===============接收救援延迟消息====================");
		log.info("接收时间:[{}],接受内容:[{}]", LocalDateTime.now(), message);

		JSONObject jsonObject = JSONObject.parseObject(message);
		String msgEnvironment = jsonObject.getString("environment");
		//当前环境
		String curEnvironment = environment.getActiveProfiles()[0];
		if (!msgEnvironment.equals(curEnvironment)) {
			return;
		}

		Integer type = jsonObject.getInteger("type");
		switch (type) {
			// 救援电话通知-超时机制处理
			case 1: {
				Long taskId = jsonObject.getLong("taskId");
				RescueNoticeTask task = rescueNoticeTaskService.getById(taskId);
				if (task == null || task.getStatus() == NoticeTaskStatusEnum.COMPLETE.getCode()) {
					return;
				}
				List<RescueNoticeTaskDetail> taskDetailList = rescueNoticeTaskDetailService.list(Wrappers.<RescueNoticeTaskDetail>lambdaQuery().eq(RescueNoticeTaskDetail::getTaskId, taskId));
				if (taskDetailList.isEmpty()) {
					return;
				}

				// 找到当前轮次（取最大轮次）
				int currentRound = taskDetailList.stream()
					.mapToInt(RescueNoticeTaskDetail::getRound)
					.max()
					.orElse(0);

				if (currentRound > 0) {
					// 超时场景：只要没有人打通(2)，其余状态均视为未打通
					rescueNoticeTaskService.checkAndNotifyNextRoundIfNeeded(task, currentRound, true);
				}
				break;
			}
			case 2: {
				// 救援告警-判断是否超时
				Long taskId = jsonObject.getLong("taskId");
				RescueNotice rescueNotice = rescueNoticeService.getById(taskId);
				if(Func.isEmpty(rescueNotice) || !Integer.valueOf(RescueNoticeConfirmTypeEnum.NOT_CONFIRM.getConfirmType()).equals(rescueNotice.getConfirmType())){
					return;
				}
				// 插入当前时间
				rescueNotice.setTimeOutTime(new Date());
				rescueNoticeService.updateById(rescueNotice);

				// 通知消息
				TenantConfig tenantConfig = tenantConfigService.getTenantConfig(rescueNotice.getTenantId());
				if (tenantConfig.getAlarmLabelConfig().getNotConfirmEnable() == 1) {
					RescueTrappedNoticeDTO noticeParam = new RescueTrappedNoticeDTO();
					noticeParam.setRescueNoticeId(rescueNotice.getId());
					noticeParam.setTenantId(rescueNotice.getTenantId());
					applicationEventPublisher.publishEvent(new RescueTrappedNoticeEvent(noticeParam));
				}
				break;
			}
			default:
				break;
		}
	}
}
